<?php

require_once dirname(__FILE__).'/../lib/newsGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/newsGeneratorHelper.class.php';

/**
 * news actions.
 *
 * @package    IPLIFE
 * @subpackage news
 * @author     alexey.shapran@gmail.com
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class newsActions extends autoNewsActions
{
	public function executeUpload(sfWebRequest $request)
	{
		
		$allowed_types = array('image/jpeg','image/gif','image/png');
		if( $file = $request->getFiles('userfile') ){
			
			if ( in_array($file['type'],$allowed_types) && is_file($file['tmp_name']) ) {
				$fileName = sha1(time()).'.'.$this->__getExtension($file['type']);
				$dest = sfConfig::get('sf_upload_dir') . DIRECTORY_SEPARATOR . $request->getParameter('object_enity') . DIRECTORY_SEPARATOR . $fileName;
				move_uploaded_file($file['tmp_name'],$dest);

				$AdditionalImage = new AdditionalImage();
				$AdditionalImage->entity_type = $request->getParameter('object_enity');
				$AdditionalImage->entity_id = $request->getParameter('object_id');
				$AdditionalImage->image = $fileName;
				$AdditionalImage->save();

				$json_response = array('imageid'=>$AdditionalImage->id,'filename'=>$fileName);
				return $this->renderText(json_encode($json_response));	
			} else {
				$err = array("error"=>"Некорректный формат. Только jpg,gif,png");
				return $this->renderText(json_encode($err));
			}
		} 
		$err = array("error"=>"Ошибка загрузки файла");
		return $this->renderText(json_encode($err));
	}

	public function executeRemove_image(sfWebRequest $request)
	{
		if( !$request->isXmlHttpRequest() )
			$this->redirect('@homepage');

		if( !$request->getParameter('image_id'))
			return $this->renderText('Не указан идентификатор картинки');

		$additional_image = Doctrine::getTable('AdditionalImage')->find($request->getParameter('image_id'));
		if( $additional_image ) {
			unlink(sfConfig::get('sf_upload_dir') . DIRECTORY_SEPARATOR . 'news' . DIRECTORY_SEPARATOR . $additional_image->image );
			//TODO: add method for deleting by hash
			$additional_image->delete();
			return $this->renderText('success');
		} 
		return $this->renderText('Ошибка удаления');
	}

	private function __getExtension($mime_type)
	{
		switch($mime_type) {
			case "image/jpeg": return 'jpg';
            break;
			case "image/gif": return 'gif';
            break;
			case "image/png": return 'png';
            break;
		} 
	}
}
